
package com.ys.chatserver.http.file.u;

import com.alibaba.fastjson.JSONObject;
import com.eva.framework.dto.DataFromServer;
import com.eva.framework.utils.LoggerFactory;
import com.google.gson.Gson;
import com.ys.chatserver.BaseConf;
import com.ys.chatserver.common.dto.cnst.EncodeConf;
import com.ys.chatserver.im.ChatServerLauncher;
import com.ys.chatserver.tool.FaceEngineUtils;
import com.ys.chatserver.tool.IdUtils;
import com.ys.chatserver.tool.ImgEqualScaleAndCutHelper;
import net.ys.mobileimsdk.server.processor.BridgeProcessor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Objects;

public class HumanFaceUploader extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final int THRESHOLD_SIZE = 1024 * 200; // 200KB    //1024 * 1024 * 3; // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 5000; //500;// 500KB     //1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = MAX_FILE_SIZE;         //1024 * 1024 * 50; // 50MB

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(THRESHOLD_SIZE);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);
            String uploadPath = BaseConf.getInstance().getDIR_HUMAN_FACE_UPLOAD();
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean res = uploadDir.mkdirs();
            }
            String fileType = request.getHeader("fileType");
            List<FileItem> formItems = upload.parseRequest(request);
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = IdUtils.get8Uuid() + "_" + new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);

                    Boolean process = process();
                    boolean result = false;

                    if (Objects.equals(fileType, "1")) {
                          result = process && !FaceEngineUtils.indentifyHumanFacePic(storeFile);
                    }

                    if (Objects.equals(fileType, "2")) {
                        // 车牌
                        // result =
                    }

                    if (result) {
                        DataFromServer objFromServer = new DataFromServer();
                        objFromServer.setReturnValue("0");
                        objFromServer.setSuccess(true);
                        objFromServer.setFileName(fileName);
                        objFromServer.setHumanFace(false);
                        sendToClient(response, objFromServer);
                        break;
                    }
                    DataFromServer objFromServer = new DataFromServer();
                    objFromServer.setReturnValue("1");
                    objFromServer.setSuccess(true);
                    objFromServer.setFileName(fileName);
                    objFromServer.setHumanFace(true);
                    sendToClient(response, objFromServer);
                    if (storeFile.exists()) {
                        File thumbnailFilePath = new File(uploadPath + File.separator + "th_" + fileName);
                        if (!thumbnailFilePath.exists()) {
                            ImgEqualScaleAndCutHelper.saveImageAsJpg(storeFile.getAbsolutePath(), thumbnailFilePath.getAbsolutePath(), 450, 450);
                        }
                    }
                    break;
                }
            }
        } catch (Exception ex) {
            LoggerFactory.getLog().error(ex.getMessage(), ex);
            DataFromServer server = new DataFromServer();
            server.setReturnValue("0");
            server.setSuccess(false);
            sendToClient(response, server);
        }
    }


    protected void sendToClient(HttpServletResponse res, DataFromServer objFromServer) throws IOException {
        String toCient = new Gson().toJson(objFromServer);
        byte[] bs = toCient.getBytes(EncodeConf.ENCODE_TO_CLIENT);
        OutputStream out = res.getOutputStream();
        out.write(bs);
        out.flush();
        out.close();
    }

    private Boolean process() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("windows")) {
            return false;
        }
        try (BufferedReader reader = new BufferedReader(new FileReader("/etc/os-release"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("VERSION_ID")) {
                    String versionId = line.split("=")[1].trim();
                    return versionId.replaceAll("\"", "").equals("7");
                }
            }
        } catch (Exception e) {
            LoggerFactory.getLog().error(e.getMessage(), e);
        }
        return false;
    }
}
